package curllook

import (
	"net/http"
	"strings"

	"goweb/ext/app"
	"goweb/ext/e"
	"goweb/service/surllook"
	"goweb/utils/commons"

	"github.com/gin-gonic/gin"
)

func CronInfo(c *gin.Context) {
	var appG = app.Gin{C: c}
	look := new(surllook.UrlLookS)
	info := look.CronInfo()
	print("info", info)
	code := e.SUCCESS
	if info == nil {
		code = e.DATA_NOT_EXIST
	}
	appG.Response(http.StatusOK, code, info)
	return
}

func AddUrlLookCron(c *gin.Context) {

	var appG = app.Gin{C: c}
	TypeFlag := c.PostForm("type")
	cid := c.PostForm("cid")

	if strings.TrimSpace(cid) == "" {
		appG.Response(http.StatusOK, e.INVALID_PARAMS, "")
		return
	}

	look := new(surllook.UrlLookS)
	err := c.ShouldBindJSON(&look)
	code := e.SUCCESS
	if !commons.CheckErr(err) {
		code = e.INVALID_PARAMS
		appG.Response(http.StatusOK, code, "")
		return
	} else if len(strings.Split(look.IP, ".")) != 4 {
		code = e.INVALID_PARAMS
	} else if !strings.HasPrefix(look.Url, "http") {
		code = e.INVALID_PARAMS
	} else if strings.TrimSpace(look.Method) == "" {
		code = e.INVALID_PARAMS
	}
	if code != e.SUCCESS {
		appG.Response(http.StatusOK, code, "")
		return
	}
	look.Id = commons.MD5(strings.TrimSpace(look.Url + strings.ToUpper(look.Method)))

	if TypeFlag == "Add" {
		code = look.AddUrlLookCronS(cid)

	} else if TypeFlag == "Update" {
		code = look.UpdateUrlLookCronS()
	} else {
		code = e.INVALID_PARAMS
	}

	appG.Response(http.StatusOK, code, "")
	return
}

/**
获取所有定时策略组
*/
func GetCronTask(c *gin.Context) {
	var appG = app.Gin{C: c}
	s := surllook.GetCronTaskS()
	code := e.SUCCESS
	if s == nil {
		code = e.DATA_NOT_EXIST
	}
	appG.Response(http.StatusOK, code, s)
	return
}
